// 获取小程序实例
const app = getApp();
Page({

    //页面的初始数据
    data: {
        loading:true,
        titleType: [
            { title: "收入", type: "sr" },
            { title: "支出", type: "zc" },
        ],
        titleTypeActive: 0,
        account: [
            {
                title: "现金",
                type: "xj"
            },
            {
                title: "微信",
                type: "wx"
            },
            {
                title: "支付宝",
                type: "zfb"
            },
            {
                title: "信用卡",
                type: "xyk"
            },
            {
                title: "储蓄卡",
                type: "cxk"
            },
        ],
        accountActive: -1,
        count: 10,
        TypeData: [],
        currentPage: -1,

        //日期范围
        dateRange: {
            start: '',
            end: ''
        },
        //日期选择
        date: '选择日期',

        //金额
        money: '',

        //备注
        comment: '',
    },

    // 生命周期函数--监听页面加载
    onLoad: function (options) {
        this.getTypeData();

        //获取当前的日期
        let end = new Date();
        let year = end.getFullYear();
        let month = end.getMonth() + 1;
        let date = end.getDate();
        month = month >= 10 ? date : '0' + date;
        this.setData({
            dateRange: {
                start: app.globalData.start,
                end: `${year}-${month}-${date}`

            }
        })

    },

    // 点击切换
    toggleClick(e) {
        //获取点击的元素的下标 index
        let currenIndex = e.currentTarget.dataset.index
        //获取控制active的数据名称
        let key = e.currentTarget.dataset.active
        //如果和当前一样点击无效
        if (this.data[key] === currenIndex) { return }
        //设置数据
        this.setData({
            [key]: currenIndex
        })
    },
    getTypeData() {

        wx.showLoading({
            title: '加载中...',
            mask: true
        })

        wx.cloud.callFunction({
            //云端的云函数名称
            name: 'get_type',

        }).then(res => {
            wx.hideLoading();
            let data = res.result.data
            let v = []
            for (let i = 0; i < data.length; i += this.data.count) {
                let o = {
                    activeIndex: -1,
                    types: data.slice(i, i + this.data.count)
                };
                v.push(o);
            }
            
            this.setData({
                TypeData: v,
                loading: false
            })
        }).catch(err => {
            
        })
    },

    toggleTypeStatus(e) {
        let currentIndex = e.currentTarget.dataset.index;

        let page = e.currentTarget.dataset.page;

        if (this.data.TypeData[page].activeIndex === currentIndex) {
            
            return;
        }

        this.data.TypeData[page].activeIndex = currentIndex;

        if (this.data.currentPage !== -1 && this.data.currentPage != page) {
            //移除其他页的激活状态
            this.data.TypeData[this.data.currentPage].activeIndex = -1;
        }

        this.data.currentPage = page;
        this.setData({
            TypeData: this.data.TypeData,
        })
    },

    //选择日期
    slectDate(e) {
        if (this.data.date === e.detail.value) {
            return
        }
        this.setData({
            date: e.detail.value
        })
    },

    //金额和备注
    inputValue(e) {

        let key = e.currentTarget.dataset.key;

        this.setData({
            [key]: e.detail.value
        })
        // 
    },
    //保存数据
    save() {

        if (app.globalData.isAuth) {



            if (this.data.currentPage === -1) {
                wx.showToast({
                    title: '选择记账类型',
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            //判断是否选择账户
            if (this.data.accountActive === -1) {
                wx.showToast({
                    title: '选择账户',
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            //判断是否选择日期
            if (this.data.date === "选择日期") {
                wx.showToast({
                    title: '选择日期',
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            //判断是否填写金额
            if (this.data.money === "选择金额") {
                wx.showToast({
                    title: '填写金额',
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            //获取记账数据
            let mainType = this.data.titleType[this.data.titleTypeActive]
            //获取记账类型
            let data = this.data.TypeData[this.data.currentPage];
            let subType = data.types[data.activeIndex];
            //获取账户
            let account = this.data.account[this.data.accountActive];
            
            wx.cloud.callFunction({
                name: 'add_booking',
                data: {
                    mainType,
                    subType,
                    account,
                    date: this.data.date,
                    money: this.data.money,
                    comment: this.data.comment
                }
            }).then(res => {
                

                if (res.result._id) {
                    wx.showToast({
                        title: '保存成功',
                        icon: "success",
                        duration: 2000
                    })
                    //清空
                    this.data.TypeData[this.data.currentPage].activeIndex = -1;

                    this.setData({
                        typeData: this.data.TypeData,
                        currentPage: -1,
                        accountActive: -1,
                        date: '选择日期',
                        money: '',
                        comment: '',
                    })
                } else {
                    wx.showToast({
                        title: '保存失败',
                        icon: "error",
                        duration: 2000
                    })
                }
            }).catch(err => {
                
            })

        } else {
            // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
            // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
            wx.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: res => {


                    //用户成功授权，将用户数据保存在数据库
                    wx.showLoading({
                        title: '加载中...',
                        mask: true
                    })

                    //调用云端的云函数
                    wx.cloud.callFunction({
                        //云端的云函数名称
                        name: 'add_userInfo',
                        data: {
                            //用户信息
                            user: res.userInfo,
                            //用户授权
                            isAuth: true
                        }
                    }).then(data => {
                        //关闭加载提示
                        wx.hideLoading();



                        if (data.result._id) {

                            app.globalData.user = res.userInfo;
                            app.globalData.isAuth = true;

                        }


                    }).catch(err => {

                    })


                }
            })

        }
        
    }

})